package com.cgc999.host.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cgc999.host.R;
import com.cgc999.host.activity.PromoteHomeActivity;
import com.cgc999.host.adapter.PromoteArticleListAdapter;
import com.cgc999.host.adapter.PromoteHomeListAdapter;
import com.cgc999.host.api.PromoteService;
import com.cgc999.host.base.BaseLazyFragment;
import com.cgc999.host.view.CgcItemDecoration;
import com.cgc999.host.vo.CgcPromoteArticle;
import com.cgc999.host.vo.ContentInfoVo;
import com.cgc999.host.vo.PageResult;
import com.cgc999.host.vo.ResponseInfo;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class FoundFragment extends BaseLazyFragment {

    List<ContentInfoVo> list;

    //公众号列表
    static XRecyclerView xRecyclerView;
    //公众号名字
    TextView txtPromoteName;
    //底部菜单布局
    LinearLayout lyPromoteHome;
    static Retrofit retrofit;

    private Activity mActivity=null;
    static SharedPreferences sharedPreferences;

    private final String TAG="FoundFragment";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        Log.i(TAG,"onCreateView");
        View view = inflater.inflate(R.layout.act_promote_home, container, false);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void reFreshData() {
        Log.i(TAG,"reFreshData");
        gainArticle(retrofit);
    }

    private void initView(View view){
        sharedPreferences= getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
        mActivity=getActivity();
        txtPromoteName=view.findViewById(R.id.txt_promote_name);
        lyPromoteHome=view.findViewById(R.id.ly_promote_home);
        xRecyclerView=view.findViewById(R.id.xr_promote_content);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xRecyclerView.setLayoutManager(layoutManager);
//      xRecyclerView.addItemDecoration(new CgcItemDecoration(this, DividerItemDecoration.VERTICAL));
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                xRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                xRecyclerView.loadMoreComplete();
            }
        });
    }

    private void initData(){
        retrofit=new Retrofit.Builder()
                .baseUrl("http://192.168.10.121:18011")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        gainArticle(retrofit);
    }

    private void gainArticle(Retrofit retrofit){
        if (retrofit==null){
            Log.i(TAG,"retrofit is null");
            return;
        }
        Log.i(TAG,"gainArticle");
        PromoteService promoteService=retrofit.create(PromoteService.class);
        String json="{   \n" +
                "\t\"open_id\": \"apUser180839080002\",\n" +
                "\t\"cur_page\":0\n" +
                "}";
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),json);
        promoteService.gainContentHomeList(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe( new Observer<ResponseInfo<PageResult<ContentInfoVo>>>(){
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i(TAG,"onSubscribe");
                    }

                    @Override
                    public void onNext(ResponseInfo<PageResult<ContentInfoVo>> s) {
                        Log.i(TAG,"onNext:"+s);
                        Log.i(TAG,"当前线程"+Thread.currentThread().getId());
                        ResponseInfo<PageResult<ContentInfoVo>> resultResponseInfo=s;
                        Log.i(TAG,"resultResponseInfo.getMsg(): " + resultResponseInfo.toString());
                        list = resultResponseInfo.getData().getList();
                        //查询的数量
                        long size=resultResponseInfo.getData().getTotal();

                        //步骤2： 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //步骤3：将获取过来的值放入文件
                        editor.putLong("articleNum", size);
                        //步骤4：提交
                        editor.commit();
                        xRecyclerView.setAdapter(new PromoteArticleListAdapter(mActivity, list));
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG,"onError");
                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG,"onComplete");
                    }
                });
    }

    @Override
    public void onStop() {
        Log.i(TAG,"onStop");
        super.onStop();
    }

    @Override
    public void onDestroy() {
        Log.i(TAG,"onDestroy");
        super.onDestroy();
    }
}
